<?php
/**
 * @user:andy
 * @date:2021/6/23
 * @company:http://www.sjdphp.com
 * @desc: 处理后台菜单
 */

namespace app\common\middleware;

use app\common\model\Menu as MenuModel;
use app\common\model\Role as RoleModel;
use app\common\server\Json;
use app\common\server\SystemLog;
use app\common\server\Tree;

class CheckAdminMenu
{
    public function handle($request,\Closure $next){
        ## 获取角色权限
        try{
            $roleInfo = RoleModel::where(array("role_id" => $request->BackInfo["role_id"],'role_status' => config("project.mysql_code.table_normal")))->find();
        }catch(\Exception $e){
            SystemLog::insertLog($e->getMessage());
        }
        if(empty($roleInfo)) return Json::error("角色不存在");

        ## 判断角色ID并获取对应的菜单数据
        if($request->BackInfo["role_id"] == 1){
            $term = [
                ['menu_status','=',config("project.mysql_code.table_normal")],
                ['menu_type','<>',3]
            ];
        }else{
            $term = [
                ['menu_id','in',$roleInfo['powers']],
                ['menu_status','=',config("project.mysql_code.table_normal")],
                ['menu_type','<>',3]
            ];

        }

        ## 查询菜单数据
        try{
            $menus = MenuModel::where($term)
                        ->field("menu_id,menu_name as title,menu_path as href,menu_icon as icon,pid,menu_sort,menu_type,menu_status")
                        ->order("menu_sort desc")
                        ->select()->toArray();
        }catch(\Exception $e){
            SystemLog::insertLog($e->getMessage());
        }

        ## 将数据存入request
        $request->MenuInit = $menus;

        ## 向下执行
        return $next($request);
    }
}